package com.heima.media.task;

import com.heima.media.service.IAuditService;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Async
public class MediaTasks {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IAuditService auditService;

    public void handleMessage() throws InterruptedException {
        RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue("article-publish");
        // 发送一条初始化的消息
        RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingQueue);
        delayedQueue.offer("init", 1, TimeUnit.SECONDS);
        while (true) {
            // 监听消息,如果没有监听到消息,会进入30秒的阻塞状态
            String result = blockingQueue.poll(30, TimeUnit.SECONDS);
                if (result != null && !result.equals("init")) {
                    System.out.println("接收到消息: " + result + " " + new Date());
                    int newsId = Integer.parseInt(result);
                    // 调用自动审核服务
                    auditService.audit(newsId);
            }
        }
    }
}
